package com.pine.manager.pineframework.trigger.impl;

import cn.hutool.core.util.StrUtil;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysUserSaveOrUpdateRequest;
import com.pine.common.trigger.AbstractTriggerTemplate;
import com.pine.common.trigger.TriggerContext;
import com.pine.common.util.user.UserInfo;
import com.pine.common.util.user.UserUtil;
import com.pine.dao.pineframework.constants.StatusEnum;
import com.pine.dao.pineframework.entity.SysUser;
import com.pine.manager.core.CipherComponent;
import com.pine.manager.core.StringPool;
import com.pine.manager.core.TriggerTypeEnum;
import com.pine.manager.pineframework.SysConfigManager;
import com.pine.manager.pineframework.SysUserManager;
import com.pine.manager.pineframework.bo.SysConfigBo;
import com.pine.manager.pineframework.bo.SysUserBo;
import com.pine.manager.pineframework.convertors.SysUserConvertor;
import com.pine.manager.pineframework.query.SysConfigQuery;
import com.pine.manager.pineframework.query.SysUserQuery;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 用户表新增或修改数据 触发器
 * </p>
 *
 * @author pine manage
 * @since 2024-08-14
 */
@Component
@Slf4j
public class SysUserSaveOrUpdateTrigger extends AbstractTriggerTemplate<SysUserSaveOrUpdateRequest, Boolean> {

    private boolean isSave;

    private SysUserBo oldSysUserBo;

    @Resource
    private SysUserManager sysUserManager;

    @Resource
    private SysUserConvertor sysUserConvertor;

    @Resource
    private CipherComponent cipherComponent;

    @Resource
    private SysConfigManager sysConfigManager;


    public SysUserSaveOrUpdateTrigger() {
        super(TriggerTypeEnum.SYS_USER_SAVE_OR_UPDATE);
    }

    @Override
    protected void before(TriggerContext<SysUserSaveOrUpdateRequest> triggerContext) {
        SysUserSaveOrUpdateRequest request = triggerContext.getTriggerRequest();
        isSave = Objects.isNull(request.getId());

        // 根据登录账号查询用户信息
        SysUserQuery query = new SysUserQuery();
        query.setLoginAccount(request.getLoginAccount());
        oldSysUserBo = sysUserManager.getOne(query);

        // 校验
        if (isSave) {
            checkOnSave();
        } else {
            checkOnUpdate();
        }
    }

    /**
     * 触发
     *
     * @param triggerContext 触发上下文
     * @return 触发结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean trigger(TriggerContext<SysUserSaveOrUpdateRequest> triggerContext) {
        // 获取请求参数
        SysUserSaveOrUpdateRequest request = triggerContext.getTriggerRequest();

        // 转换为业务对象，并设置额外字段
        SysUserBo newSysUserBo = sysUserConvertor.saveRequestToEntityBo(request);
        // 设置用户信息
        setUserInfo(newSysUserBo);
        // 设置密码
        setPassword(newSysUserBo);

        // 转换为实体
        SysUser sysUser = sysUserConvertor.entityBoToEntity(newSysUserBo);

        // 新增
        if (isSave) {
            return sysUserManager.save(sysUser);
        }

        // 修改
        sysUser.setId(oldSysUserBo.getId());
        // 此处不修改密码
        sysUser.setPassword(oldSysUserBo.getPassword());
        return sysUserManager.updateById(sysUser);
    }

    private void checkOnSave() {
        // 校验用户是否已存在
        if (Objects.nonNull(oldSysUserBo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_EXIST);
        }
    }

    private void checkOnUpdate() {
        // 校验用户是否不存在
        if (Objects.isNull(oldSysUserBo)) {
            throw new BusinessException(ExceptionCodeEnum.USER_NOT_EXIST);
        }
    }

    private void setUserInfo(SysUserBo sysUserBo) {
        UserInfo userInfo = UserUtil.get();
        if (Objects.nonNull(userInfo)) {
            if (isSave) {
                sysUserBo.setCreateUserId(userInfo.id());
            }
            sysUserBo.setUpdateUserId(userInfo.id());
        }
    }

    private void setPassword(SysUserBo sysUserBo) {
        if (isSave) {
            // 密码为空时，使用系统配置中的默认密码
            if (StrUtil.isBlank(sysUserBo.getPassword())) {
                // 查询sys_config中配置的默认密码
                SysConfigQuery sysConfigQuery = new SysConfigQuery();
                sysConfigQuery.setConfigKey(StringPool.SYS_CONFIG_DEFAULT_PASSWORD);
                sysConfigQuery.setStatus(StatusEnum.ENABLE);
                SysConfigBo sysConfigBo = sysConfigManager.getOne(sysConfigQuery);
                // 若查询到配置信息，设置配置中的默认密码为当前新增用户的密码
                if (Objects.nonNull(sysConfigBo)) {
                    String defaultPassword = sysConfigBo.getConfigValue();
                    sysUserBo.setPassword(cipherComponent.aesEncrypt(defaultPassword));
                } else {
                    String defaultPassword = "123456";
                    log.warn("系统配置中没有配置默认密码，账号{}将使用默认密码为：{}", sysUserBo.getLoginAccount(), defaultPassword);
                    sysUserBo.setPassword(cipherComponent.aesEncrypt(defaultPassword));
                }
                return;
            }

            // 密码不为空时，直接加密
            sysUserBo.setPassword(cipherComponent.aesEncrypt(sysUserBo.getPassword()));
        }
    }
}
